// pages/welcome/welcome.js

const APP_ID = 'wxcdf0cf9fcd4e0fc7'; //输入小程序appid
const APP_SECRET = '596e5dad3550a055a282c90035b2cedc'; //输入小程序app_secret
var OPEN_ID = '' //储存获取到openid
var SESSION_KEY = '' //储存获取到session_key
/**
 * 页面的初始数据
 */
function getOpenid(wxUserInfo,cb) {
  wx.login({
    success: function(res) {
      wx.request({
        //获取openid接口
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        data: {
          appid: APP_ID,
          secret: APP_SECRET,
          js_code: res.code,
          grant_type: 'authorization_code'
        },
        method: 'GET',
        success: function(res) {
          if (res.statusCode == 200 && res.data) {
            OPEN_ID = res.data.openid; //获取到的openid
            SESSION_KEY = res.data.session_key; //获取到session_key
            wxUserInfo.openid = OPEN_ID;
            wxUserInfo.session_key = SESSION_KEY;
            if(typeof cb == 'function'){
              cb(wxUserInfo);
            }
          }
        }
      })
    }
  })
}

module.exports = {
  getOpenid: getOpenid
}